<!DOCTYPE html>
<html>

<head>
    <title>stomp</title>
</head>

<body>
Welcome<br/><input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="subscribe2()">subscribe2/topic/mess</button>
<button onclick="subscribe1()">subscribe1/topic/mess</button>
<hr/>
<button onclick="closeWebSocket()">close web socket</button>
<hr/>
<div id="message"></div>
</body>

<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="@{https://code.jquery.com/jquery-3.2.0.min.js}"></script>
<script type="text/javascript">
    // 建立连接对象（还未发起连接）
    var socket = new SockJS("http://localhost:8080/public/server");

    // 获取 STOMP 子协议的客户端对象
    var stompClient = Stomp.over(socket);

    // 向服务器发起websocket连接并发送CONNECT帧
    stompClient.connect(
        {},
        function connectCallback(frame) {
            // 连接成功时（服务器响应 CONNECTED 帧）的回调方法
            setMessageInnerHTML("connect success");
<!--            stompClient.subscribe('/subscribeTest', function (response) {-->
<!--                setMessageInnerHTML("success subscribe /subscribeTest");-->
<!--                var returnData = JSON.parse(response.body);-->
<!--                console.log('Connected:' + frame);-->
<!--                console.log(response.body);-->
<!--                setMessageInnerHTML("/subscribeTest message:" + returnData.responseMessage);-->
<!--            });-->
        },
        function errorCallBack(error) {
            // 连接失败时（服务器响应 ERROR 帧）的回调方法
            setMessageInnerHTML("连接失败");
        }
    );

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        var messageJson = JSON.stringify({ "content": message,"fromUserId":"dyp","toUserId":"yz" });
        stompClient.send("/send/to/all", {}, messageJson);
        setMessageInnerHTML("/send/to/all you seed message:" + message);
    }

    //订阅消息
    function subscribe1() {
        stompClient.subscribe('/subscribeTest', function (response) {
            setMessageInnerHTML("sub success /subscribeTest");
            var returnData = JSON.parse(response.body);
            setMessageInnerHTML("/subscribeTest you received message1:" + returnData.responseMessage);
        });
    }

    //订阅消息
    function subscribe2() {
        stompClient.subscribe('/subscribeTest', function (response) {
            setMessageInnerHTML("sub success/subscribeTest");
            var returnData = JSON.parse(response.body);
            setMessageInnerHTML("/subscribeTest you received message2:" + returnData.responseMessage);
        });
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

</script>

</html>